package array.prefixsum;

public class PivotIndex {

    public int pivotIndex(int[] nums) {
        int n = nums.length;
        int[] preSum = new int[n + 1];
        // 计算 nums 的前缀和
        for (int i = 1; i <= n; i++) {
            preSum[i] = preSum[i - 1] + nums[i - 1];
        }
        // 根据前缀和判断左半边数组和右半边数组的元素和是否相等
        for (int i = 1; i <= n; i++) {
            // 计算nums[i - 1] 左侧和右侧元素和
            int leftSum = preSum[i - 1] - preSum[0];
            int rightSum = preSum[n] - preSum[i];
            if (leftSum == rightSum)
                // 相对 nums 数组，preSum 数组有一位索引偏移
                return i - 1;
        }

        return -1;
    }
}
